import time
import json
import requests

from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import QThread, pyqtSignal, Qt

from ui.counter import Ui_MainWindow

from bases import globalvar
from bases.player import SoundPlayer
from libs.counter import ImageCounter
from libs.qrcode import Qrcode
from libs.ioctrl import IoCtrl

'''
    计数器 计数业务代码写到这里
'''
class CounterMainWindow(QMainWindow):

    changeNumSignal = pyqtSignal(int)
    changeInfoSignal = pyqtSignal(str)

    #二维码解析结果的缓存
    jsondict = {}

    def __init__(self):
        QMainWindow.__init__(self)  # QMainWindow的初始化
        self.main_ui = Ui_MainWindow()  # 主窗口的实例化
        self.main_ui.setupUi(self)

        '''
            多线程下，其他线程无法直接更新UI线程，需要用pyqt的信号(signal)
        '''
        self.delayThread = UiDelay()
        self.delayThread.timeoutSignal.connect(self.delayClear)

        self.http = NetReqeust()
     

        self.changeNumSignal.connect(self.changeNumberCallback)
        self.changeInfoSignal.connect(self.changeInfomationCallback)

        self.delayThread.start()
        
        globalvar._init()
        SoundPlayer.init()    

    '''
        延迟清空考场与计数
    '''
    def delayClear(self):
        self.main_ui.infomation.setText("")
        self.main_ui.number.setText("")
     
    '''
        更新显示计数值
    '''
    def changeNumber(self, num):
        self.changeNumSignal.emit(num)
        self.jsondict['checkNum'] = num
        self.http.post(self.jsondict)

 

    def changeNumberCallback(self, num):
        _translate = QtCore.QCoreApplication.translate
        self.main_ui.number.setText(_translate("MainWindow",
                "<html><head/><body><p align=\"center\">"+str(num)+"</p></body></html>"))
                
        self.delayThread.start()
    '''
        扫描二维码后更新考察信息显示
    '''
    # def changeInfomation(self, jsonStr):
    #     try:
    #         jsonmap = json.loads(jsonStr)
    #     except json.decoder.JSONDecodeError as e:
    #         self.changeInfoSignal.emit('无法识别的二维码')
    #         self.delayThread.start()
    #         return
        
    #     self.jsondict = jsonmap
    #     self.changeInfoSignal.emit(jsonmap['code'] + ' - ' + jsonmap['subject'])
    
    
    def changeInfomationCallback(self, txt):
        _translate = QtCore.QCoreApplication.translate
        self.main_ui.infomation.setText(_translate("MainWindow",
                "<html><head/><body><p align=\"center\">"+txt+"</p></body></html>"))
    
    def keyPressEvent(self, event:QtGui.QKeyEvent):
        print("按下：" + str(event.key()))
#退出键定义
        if(event.key() == Qt.Key_Escape):
            self.close()
            print('测试：退出')
#计数键定义
        if(event.key() == 16777220):
            count = ImageCounter.capAndAnalysis()
            self.changeNumber(count)
            SoundPlayer.play(count)
            print('测试：计数')
#二维码功能调用
        if(event.key() == Qt.Key_0):
            print('测试：0')
            brs = Qrcode.detect()
            if(brs is not None):
                self.changeInfomation(brs[0])
        if(event.key() == Qt.Key_1):
            print('测试：1')
        if(event.key() == Qt.Key_2):
            print('测试：2')
        if(event.key() == Qt.Key_3):
            print('测试：3')
        if(event.key() == Qt.Key_4):
            print('测试：4')
        if(event.key() == Qt.Key_5):
            print('测试：5')
        if(event.key() == Qt.Key_6):
            print('测试：6')
        if(event.key() == Qt.Key_7):
            print('测试：7')
        if(event.key() == Qt.Key_8):
            print('测试：8')
        if(event.key() == Qt.Key_9):
            print('测试：9')
'''
    UI 后台线程, 延迟清空显示的内容
'''
class UiDelay(QThread):
    # 定义信号,定义参数为str类型
    timeoutSignal = pyqtSignal()
    
    def __init__(self, parent=None):
        super().__init__(parent)

        # 下面的初始化方法都可以，有的python版本不支持
        # super(Mythread, self).__init__()
    
    def run(self):
        time.sleep(4)
        self.timeoutSignal.emit()

REQUEST_URL = "http://xhsaas.com/answer-sheet/api/client/checkNum"
HEADER = {'Content-Type':'application/json; charset=utf-8'}

'''
   网络请求线程，UI线程可能不允许进行网络请求（阻塞UI更新）
'''
class NetReqeust(QThread):
    # 定义信号,定义参数为str类型
    requestSignal = pyqtSignal(int)
    
    formBody = {}

    def __init__(self, parent=None):
        super().__init__(parent)

        # 下面的初始化方法都可以，有的python版本不支持
        # super(Mythread, self).__init__()
    
    def post(self, body):
        self.formBody = body
        self.start()

    def run(self):
        self.requestSignal.emit(1)
        rsp = requests.post(REQUEST_URL, data=json.dumps(self.formBody), headers=HEADER)
        print(rsp)
        # if rsp.status_code == 200:
        #     return True
        # else:
        #     return False
        self.requestSignal.emit(2)